//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using OpenLS.Core.Formatting;

namespace OpenLS.Core
{
    public class FractionFormat: Format
    {
        public FractionFormat(string code): base (code)
        {
            string str = code;
            str = str.Replace(" ", "");
            str = str.Replace("#", "");
            string[] ss = str.Split('/');
            if (ss.Length != 2)
                throw new ArgumentException("code");
            if (int.TryParse(ss[1], out denominator))
            {
            }
            else{
                denominator = 0;
                denominatorFormat = ss[1];
                maxDenominator = 10 ^ denominatorFormat.Length;
            }

        }
        int denominator;
        readonly int maxDenominator;
        string denominatorFormat;

        public override object GetFormattedValue(object o, IFormatValueConverter converter)
        {
            if (o is double)
            {
                double dbl = (double)o;
                Fraction f;
                if (denominator != 0)
                {
                    f = Fraction.Calculate(dbl, denominator);
                    return f.ToString();
                }
                f = Fraction.FindClosest(dbl, maxDenominator);
                return f.ToString();
                
            }
            return o;
        }

        public override bool CanFormat(object o)
        {
            return (o is double);
        }

        internal override void Analyze(List<FormatToken> list)
        {
            if (list.Count == 5)
            {
                object o3 = list[4];
                if (o3 is NumericToken)
                {
                    denominator = 0;
                    denominatorFormat = ((NumericToken)o3).Value;
                }
                else if (o3 is IntegerToken)
                {
                    denominator = ((IntegerToken)o3).Value;

                }
                else
                    throw new NotImplementedException();
            }
            else
                throw new NotImplementedException();

        }

        public override FormatCategory Category
        {
            get { return FormatCategory.Fraction ; }
        }
    }
}
